//
//  RegisterViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "RegisterViewController.h"


@interface RegisterViewController ()

@property (nonatomic, strong) UITextField *phoneTF;
@property (nonatomic, strong) UITextField *verifyTF;
@property (nonatomic, strong) UITextField *passwordTF;
@property (nonatomic, strong) UIButton *registerButton;
@property (nonatomic, strong) UIButton *codeButton;
@property (nonatomic, strong) UIButton *protocoButton;
@property (nonatomic, strong) UIImageView *phoneIcon;
@property (nonatomic, strong) UIImageView *lockIcon;
@property (nonatomic, strong) UIImageView *codeIcon;
@property (nonatomic, strong) UIView *line1;
@property (nonatomic, strong) UIView *line2;
@property (nonatomic, strong) UIView *line3;
@property (nonatomic, strong) UILabel *tipsLabel;


@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 

}

- (void) viewDidAppear:(BOOL)animated {
//    if ([DTCEXRACT_OBJECT(REGISTER) isEqualToString:@"YES"]) {
//        UploadAvatarViewController *vc = [[UploadAvatarViewController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//    }
}

- (void)refreshBaseControlValue
{
    
    [self setNavigationTitle:@"注册" titleColor:[UIColor colorWithHexString:@"#585D6D"]];
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back_nor"]];
    
    [self layoutSubviews];
    //    [self.view addSubview:self.iconImageView];
}


- (void)layoutSubviews{
    CGFloat edge = px1080Width(100);
    
    [self.line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(px1920Height(400));
        make.left.equalTo(self.view).with.offset(edge);
        make.right.equalTo(self.view).with.offset(-edge);
        make.height.mas_equalTo(1);
    }];
    
    
    [self.phoneIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(edge);
        make.bottom.mas_equalTo(self.line1).with.offset(-px1920Height(16));
        make.width.mas_equalTo(px1080Width(60));
        make.height.mas_equalTo(px1920Height(60));
    }];
    
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.line1).with.offset(-px1920Height(16));
        make.height.mas_equalTo(px1920Height(60));
        make.left.equalTo(self.phoneIcon.mas_right).with.offset(px1080Width(36));
        make.right.equalTo(self.view).with.offset(-edge);
    }];
    
    
    [self.line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line1.mas_bottom).with.offset(px1920Height(157));
        make.left.equalTo(self.view).with.offset(edge);
        make.right.equalTo(self.view).with.offset(-edge);
        make.height.mas_equalTo(1);
    }];
    
    
    
    [self.codeIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(edge);
        make.bottom.mas_equalTo(self.line2).with.offset(-px1920Height(16));
        make.width.mas_equalTo(px1080Width(60));
        make.height.mas_equalTo(px1920Height(60));
    }];
    
    [self.codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.line2).with.offset(-px1920Height(16));
        make.right.equalTo(self.view).with.offset(-edge);
        make.height.mas_equalTo(px1920Height(60));
        make.width.mas_equalTo(px1080Width(300));
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithHexString:@"#CACACA"];
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.line2).with.offset(-px1920Height(16));
        make.height.mas_equalTo(px1920Height(60));
        make.right.equalTo(self.codeButton.mas_left).with.offset(-px1080Width(40));
        make.width.mas_equalTo(px1080Width(2));
    }];
    

    [self.verifyTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.line2).with.offset(-px1920Height(16));
        make.height.mas_equalTo(px1920Height(60));
        make.left.equalTo(self.codeIcon.mas_right).with.offset(px1080Width(36));
        make.right.equalTo(line.mas_left).with.offset(-px1080Width(40));
    }];
    
    [self.line3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line2.mas_bottom).with.offset(px1920Height(157));
        make.left.equalTo(self.view).with.offset(edge);
        make.right.equalTo(self.view).with.offset(-edge);
        make.height.mas_equalTo(1);
    }];
    
    [self.lockIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(edge);
        make.bottom.mas_equalTo(self.line3).with.offset(-px1920Height(16));
        make.width.mas_equalTo(px1080Width(60));
        make.height.mas_equalTo(px1920Height(60));
    }];
    
    [self.passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.line3).with.offset(-px1920Height(16));
        make.height.mas_equalTo(px1920Height(60));
        make.left.equalTo(self.phoneIcon.mas_right).with.offset(px1080Width(36));
        make.right.equalTo(self.view).with.offset(-edge);
    }];
    
    
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.line3.mas_bottom).with.offset(px1920Height(80));
        make.left.equalTo(self.view).with.offset(edge);
        make.right.equalTo(self.view).with.offset(-edge);
        make.height.mas_equalTo(px1920Height(136));
    }];
    
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.registerButton.mas_bottom).with.offset(px1920Height(41));
        make.right.equalTo(self.view.mas_centerX);
        make.left.equalTo(self.view);
        make.height.mas_equalTo(36);

    }];
    
    [self.protocoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.registerButton.mas_bottom).with.offset(px1920Height(41));
        make.left.equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(px1080Width(500));
//        make.right.equalTo(self.view);
        make.height.mas_equalTo(36);
    }];
    
}

#pragma mark -- 懒加载
- (UITextField *)phoneTF
{
    if(!_phoneTF)
    {
        _phoneTF = [[UITextField alloc]init];
        _phoneTF.placeholder = @"请输入手机号码";
        _phoneTF.keyboardType = UIKeyboardTypePhonePad;
        [self.view addSubview:_phoneTF];
    }
    return _phoneTF;
}

- (UITextField *)verifyTF
{
    if(!_verifyTF)
    {
        _verifyTF = [[UITextField alloc]init];
        _verifyTF.keyboardType = UIKeyboardTypePhonePad;
        _verifyTF.placeholder = @"请输入验证码";
        [self.view addSubview:_verifyTF];
    }
    return _verifyTF;
}

- (UITextField *)passwordTF
{
    if(!_passwordTF)
    {
        _passwordTF = [[UITextField alloc]init];
        _passwordTF.placeholder = @"请输入密码";
        _passwordTF.secureTextEntry = YES;
        [self.view addSubview:_passwordTF];
    }
    return _passwordTF;
}

- (UIImageView *)phoneIcon
{
    if(!_phoneIcon)
    {
        _phoneIcon = [[UIImageView alloc]init];
        _phoneIcon.image = [UIImage imageNamed:@"icon_phone"];
        _phoneIcon.contentMode = UIViewContentModeScaleAspectFit;
        [self.view addSubview:_phoneIcon];
    }
    return _phoneIcon;
}

- (UIImageView *)lockIcon
{
    if(!_lockIcon)
    {
        _lockIcon = [[UIImageView alloc]init];
        _lockIcon.image = [UIImage imageNamed:@"icon_icon_password"];
        _lockIcon.contentMode = UIViewContentModeScaleAspectFit;
        [self.view addSubview:_lockIcon];
    }
    return _lockIcon;
}

- (UIImageView *)codeIcon
{
    if(!_codeIcon)
    {
        _codeIcon = [[UIImageView alloc]init];
        _codeIcon.image = [UIImage imageNamed:@"icon_verify"];
        _codeIcon.contentMode = UIViewContentModeScaleAspectFit;
        [self.view addSubview:_codeIcon];
    }
    return _codeIcon;
}

- (UIView *)line1
{
    if(!_line1)
    {
        _line1 = [[UIView alloc]init];
        _line1.backgroundColor = [UIColor colorWithHexString:@"#CACACA"];
        [self.view addSubview:_line1];
    }
    return _line1;
}
- (UIView *)line2
{
    if(!_line2)
    {
        _line2 = [[UIView alloc]init];
        _line2.backgroundColor = [UIColor colorWithHexString:@"#CACACA"];
        [self.view addSubview:_line2];
        
    }
    return _line2;
}

- (UIView *)line3
{
    if(!_line3)
    {
        _line3 = [[UIView alloc]init];
        _line3.backgroundColor = [UIColor colorWithHexString:@"#CACACA"];
        [self.view addSubview:_line3];
        
    }
    return _line3;
}

- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
        UIView *superView = self.view;
        _tipsLabel = [[UILabel alloc]init];
        _tipsLabel.textAlignment = NSTextAlignmentRight;
        [superView addSubview:_tipsLabel];
        [_tipsLabel setFont:[UIFont systemFontOfSize:14]];
        [_tipsLabel setTextColor:[UIColor colorWithHexString:@"#6F6F6F"]];
        _tipsLabel.text = @"注册完成即表示同意";
    }
    return _tipsLabel;
}


- (UIButton *)codeButton
{
    if(!_codeButton)
    {
        _codeButton = [[UIButton alloc]init];
        [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_codeButton setTitleColor:[UIColor colorWithHexString:@"#3E76F6"] forState:UIControlStateNormal];
        [_codeButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
        [_codeButton addTarget:self action:@selector(didClickCodeButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_codeButton];
    }
    return _codeButton;
}



- (UIButton *)registerButton
{
    if(!_registerButton)
    {
        _registerButton = [[UIButton alloc]init];
        [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
//        [_registerButton setTitleColor:[UIColor colorWithHexString:@"#3E76F6"] forState:UIControlStateNormal];
        //        [_registerButton.titleLabel setFont:<#(UIFont * _Nullable)#>];
        [_registerButton setBackgroundImage:[UIImage imageNamed:@"button_login_nor"] forState:UIControlStateNormal];
        [_registerButton setBackgroundImage:[UIImage imageNamed:@"button_login_sel"] forState:UIControlStateHighlighted];
        [_registerButton addTarget:self action:@selector(didClickRegisterButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_registerButton];
    }
    return _registerButton;
}

- (UIButton *)protocoButton
{
    if(!_protocoButton)
    {
        _protocoButton = [[UIButton alloc]init];
        [_protocoButton setTitle:@"《日沛科技用户协议》" forState:UIControlStateNormal];
        [_protocoButton setTitleColor:[UIColor colorWithHexString:@"#3E76F6"] forState:UIControlStateNormal];
        [_protocoButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [_protocoButton addTarget:self action:@selector(didClickProtocoButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_protocoButton];
    }
    return _protocoButton;
}

#pragma mark -- 事件
- (void)didClickProtocoButton {
    WebViewController *vc = [[WebViewController alloc] init];
    vc.title = @"用户协议";
    vc.type = 2;

    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didClickCodeButton {
    if (![_phoneTF.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码.."];
        return;
    }
    
    [self getVerifyCodeNumber];
}

// 获得验证码
- (void)getVerifyCodeNumber {
    [SVProgressHUD showInfoWithStatus:@"正在获取验证码..."];
    
    GetRegisterCodeApi * codeApi = [[GetRegisterCodeApi alloc] initWithDic:@{@"username":self.phoneTF.text}];
    [codeApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary * codeDic = [request responseJSONObject];
        NSLog(@"code Dic == %@ ",codeDic);
        //        [codeApi analyseResponseObject];
        
        if ([codeDic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showInfoWithStatus:codeDic[@"errmsg"]];
            [self setVerifyBtnTimer];
            DTCSAVE_OBJECT(codeDic[@"vcode"], @"vcode");
        }else{
            [SVProgressHUD showErrorWithStatus:codeDic[@"errmsg"]];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showErrorWithStatus:@"请求超时"];
    }];
}

// 设置定时器
- (void)setVerifyBtnTimer {
    __block int code_out = 60;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (code_out <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [_codeButton setTitle:@"获取验证码" forState:0];
                [_codeButton setTitle:@"60秒后获取" forState:UIControlStateDisabled];
                _codeButton.enabled = YES;
                code_out = 60;
            });
        } else {
            _codeButton.enabled = NO;
            NSString * time = [NSString stringWithFormat:@"%d秒后获取",code_out];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_codeButton setTitle:time forState:UIControlStateDisabled];
            });
            code_out -- ;
        }
    });
    dispatch_resume(timer);
}

- (void)didClickRegisterButton {
    if (_phoneTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号码不能为空"];
        return;
    }
    
    if (![_phoneTF.text isMobileNumber]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码.."];
        return;
    }

    
    if (_verifyTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"亲，还未输入验证码..."];
        return;
    }
    
    if (_verifyTF.text.length < 6 || _verifyTF.text.length > 6) {
        [SVProgressHUD showErrorWithStatus:@"亲，请输入6位验证码..."];
        return;
    }
    
    
    if (![_passwordTF.text isRegexPassword]) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-20位字母或数字密码\n不包含除_@.之外的特殊符号"];
        return;
    }
    
    if (_passwordTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-18位密码"];
        return;
    }
    
    if (_passwordTF.text.length < 6 || _passwordTF.text.length > 18) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-18位密码"];
        return;
    }
    
    [self registerActionStart];

}

// 开始注册
- (void)registerActionStart
{
    RegisterApi * registerApi = [[RegisterApi alloc] initWithDic:@{@"username":self.phoneTF.text,@"password":self.passwordTF.text,@"vcode":self.verifyTF.text}];
    [registerApi startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSDictionary *dict = [request responseJSONObject];
        if ([dict[@"errcode"] intValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:dict[@"errmsg"]];
//            [self backBtnAction:nil];
//            [SVProgressHUD showSuccessWithStatus:@"您已注册成功！"];
            DTCSAVE_OBJECT(self.phoneTF.text , USERNAME);
            DTCSAVE_OBJECT(self.passwordTF.text, PASSWORD);
            DTCSAVE_OBJECT(dict[@"data"][@"uid"], UID);
            DTCSAVE_OBJECT(dict[@"data"][@"token"], TOKEN);
            DTCSAVE_OBJECT(dict[@"data"][@"image"], IMAGE);
//            DTCSAVE_OBJECT(@"YES", @"Login");   // 登录状态保存来设置根控制器
            DTCSAVE_OBJECT(@"1", REGISTER);

            UploadAvatarViewController *vc = [[UploadAvatarViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:dict[@"errmsg"]];
        }
    } failure:^(YTKBaseRequest *request) {
        [SVProgressHUD showInfoWithStatus:@"请求超时"];
    }];
}

#pragma mark - 返回按钮点击
- (IBAction)backBtnAction:(id)sender {
    
    NSArray * viewcontrollers = self.navigationController.viewControllers;
    if (viewcontrollers.count > 1) {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count-1] == self) {
            [self.navigationController popViewControllerAnimated:YES];  //push方式
        }
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];   //present方式
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
